<template>
  <div>
    <van-search
      v-model="searchTxt"
      show-action
      label="商品"
      placeholder="请输入搜索关键词"
      background="#ff734c"
      @search="onSearch"
    >
      <template #action>
        <div class="search-text" @click="onSearch">搜索</div>
      </template>
    </van-search>
    <h2>搜索记录</h2>
    <div class="histories">
      <div class="his" @click="clickHis(item)" v-for="item in his" :key="item">
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script>
/*
  缓存 存 his []
  存  JSON.stringify()
  取：
    const his = localStorage.getItem('his')
                ?
                JSON.parse(localStorage.getItem('his'))
                :
                []
*/
export default {
  name: 'search',
  data () {
    return {
      searchTxt: '',
      his: localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
    }
  },
  methods: {
    clickHis (txt) {
      this.searchTxt = txt
      this.onSearch()
    },
    onSearch () {
      /*
      跳转到 搜索结果页，并将 查询 关键字传入
      */
      // 添加历史记录
      /*
        先取缓存 转换成数组
        操作数组
        存回去
      */
      let his = localStorage.getItem('his')
        ? JSON.parse(localStorage.getItem('his'))
        : []
      his.unshift(this.searchTxt)
      his = [...new Set(his)]
      his.length = 5
      // 存回去
      localStorage.setItem('his', JSON.stringify(his))
      this.$router.push({
        path: '/searchLists',
        query: {
          keyWord: this.searchTxt
        }
      })
    }
  },
  mounted () {
    console.log(this.$route)
  }
}
</script>

<style lang="scss" scoped>
.search-text {
  color: #fff;
}
.histories {
  margin-top: 30px;
  display: flex;
  flex-wrap: wrap;
  .his{
    font-size: 16px;
    color: #333;
    line-height: 30px;
    padding: 0 10px;
  }
}
</style>
